package com.itsc.action;

import com.itsc.entities.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;
import com.itsc.service.inter.ILoginService;
import com.itsc.service.inter.IUserService;
import com.itsc.util.MD5Util;

public class AdminLoginAction implements ModelDriven<User> {

	private User model = new User();
	private ILoginService loginService;
	private IUserService userService;
	private String code;
	
	@Override
	public User getModel() {
		// TODO Auto-generated method stub
		return model;
	}
	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public void setLoginService(ILoginService loginService) {
		this.loginService = loginService;
	}

	public String login() throws Exception {

		if (code == null || code.equals("")) {
			ActionContext.getContext().put("error", "验证码不能为空");
			ActionContext.getContext().put("user", model);
			return "loginInsert";
		} else if (!loginService.checkCode(code)) {
			ActionContext.getContext().put("error", "验证码错误");
			ActionContext.getContext().put("user", model);
			return "loginInsert";
		}
		Boolean flag = loginService.checkUser(model.getUser_name(),
				MD5Util.getStringMD5(model.getUser_pwd()));
		User user = loginService.QueryUser(model.getUser_name(),
				MD5Util.getStringMD5(model.getUser_pwd()));
		if (flag) {
			if(user.getUser_level()!=null && !user.getUser_level().equals("")
					&& user.getUser_level()==0){
				ActionContext.getContext().put("error", "该用户没有登录权限");
				ActionContext.getContext().put("user", model);
				return "loginInsert";
			}else{
				ActionContext.getContext().getSession().put("user", user);
				return "login";
			}
			
		} else {
			ActionContext.getContext().put("error", "用户名或者密码错误");
			ActionContext.getContext().put("user", model);
			return "loginInsert";
		}
	}

	public String checkCode() throws Exception {
		String recode = (String) ActionContext.getContext().getSession()
				.get("securityCode");

		if (code != null && !code.equals("") && !recode.equals("")
				&& recode != null && code.equals(recode)) {
			ServletActionContext.getResponse().getWriter().print("0");
		} else {
			ServletActionContext.getResponse().getWriter().print("1");
		}

		return null;
	}
}
